#include <wxtl/base.h>
#include "Fiber.h"

namespace wxtl
{
	size_t Fiber::s_total = 0;

	Fiber::Fiber(void* parent)
		:m_parent(parent)
		,m_finished(false)
	{
		m_fiber = CreateFiber(0,(LPFIBER_START_ROUTINE)FiberProc,(void*)this);
		s_total++;
	}

	Fiber::Fiber()
		:m_finished(false)
	{
		m_fiber = ::ConvertThreadToFiber((void*)this);

	}

	Fiber::~Fiber(void)
	{
		::DeleteFiber(m_fiber);
		s_total--;
	}

	Fiber* Fiber::Init()
	{
		return new Fiber();
	}

	bool Fiber::IsFinished()
	{
		return m_finished;
	}

	void Fiber::FiberProc(PVOID lpParameter)
	{
		Fiber* self = (Fiber*)lpParameter;
		self->Run();
		self->m_finished = true;
		self->Y();
	}

	void Fiber::Run()
	{
		MessageBox(NULL,L"Fiber",NULL,MB_OK);
	}

	void Fiber::Switch()
	{
		SwitchToFiber(m_fiber);
	}

	void Fiber::Y()
	{
		SwitchToFiber(m_parent);
	}

	Fiber& Fiber::Current()
	{
		return *((Fiber*)GetFiberData());
	}

	void Fiber::SetParent( Fiber* parent )
	{
		m_parent = parent->m_fiber;
	}
}

